package com.kc.gb.device.plugins.strip.starter;

import com.kc.gb.base.dto.DeviceType;
import com.kc.gb.base.dto.Result;
import com.kc.gb.device.common.dto.RefreshUIEvent;
import com.kc.gb.device.common.interfaces.IHardware;
import com.kc.gb.device.common.properties.DeviceProperties;
import com.kc.gb.device.common.utils.SpringHelper;
import com.kc.gb.device.plugins.strip.service.StripMQService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author : GlobalApplicationRunner
 * @version V1.0
 * @date: 2023/11/29 10:55 AM
 * @Description: TODO
 */
@Slf4j
@Configuration
public class StripApplicationRunner implements ApplicationRunner {

    @Resource
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    DeviceProperties deviceProperties;

    @Resource
    StripMQService stripMQService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        IHardware hardware = (IHardware) SpringHelper.getApplicationContext().getBean(DeviceType.STRIP.name());
        if(!hardware.isEnabled()){
            log.info("DeviceStripEnabled:{}",hardware.isEnabled());
            return;
        }
        // Strip 建立硬件连接
        threadPoolTaskExecutor.execute(()->{
            Result<?> result = null;
            try {
                result = hardware.initialize();
            } catch (Throwable e) {
                log.error("StripHardware:{}",e.getMessage(),e);
                result = Result.fail(e.getClass().getSimpleName());
            }
            // 保存初始化的结果
            try {
                hardware.afterInitialize(result);
                SpringHelper.getApplicationContext().publishEvent(new RefreshUIEvent(DeviceType.STRIP));
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        });

        // Strip 灯带只接受MQ, 没有回传效果
        threadPoolTaskExecutor.execute(()->{
            try {
                stripMQService.createCommandConsumer();
            } catch (Exception e) {
                log.error("MQService create consumer:{}",e.getMessage(),e);
            }
        });
    }
}
